# -*- coding: utf-8 -*-
from django.core import serializers
from django.core.urlresolvers import reverse
from django.core.paginator import Paginator, InvalidPage
from django.contrib import messages
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import User
from django.http import HttpResponse, Http404, HttpResponseRedirect, HttpResponseServerError, Http404
from django.shortcuts import render_to_response, render, get_object_or_404, RequestContext
from django.template import Context, loader
from dmblog.mblog.forms import *
from dmblog.mblog.models import *
from dmblog.utils import mailer, formatter, uploader, paginatorer, function
from settings import *

ITEMS_PRE_PAGE = 7


def index(request):
    if not request.user.is_authenticated():
        return render_to_response('index.html',{'STATIC_URL': STATIC_URL, 'MEDIA_URL': MEDIA_URL})
    else:
        return HttpResponseRedirect(reverse('mblog_home'))

# 用户首页，显示Feed新鲜事


@login_required(login_url='/accounts/signin')
def home(request):

    if request.method == 'POST':
        form = PostForm(request.POST)
        if form.is_valid():
            message = form.cleaned_data['message']
            t = Tweet.objects.create(message=message, user=request.user)
            messages.info(request, u'发送成功!')
            return HttpResponseRedirect(reverse('mblog_home'))
        else:
            messages.info(request, u'发送失败!')
    else:
        form = PostForm()
        rtform = RTForm()

    followerslist = [f.followers for f in request.user.follower_set.all()]
    followerslist = list(followerslist)
    followerslist.append(request.user)

    tweets = Tweet.objects.filter(user__in=followerslist).order_by('-addtime')

    paginator_info = paginatorer.paginator_parse(
        request, tweets, ITEMS_PRE_PAGE)

    taruser = request.user

    tartweet = Tweet.objects.filter(user=taruser).order_by('addtime')

    varibles = RequestContext(request, {
        'form': form,
        'tweets': paginator_info['curremt_obj'],
        'paginator': paginator_info,
        'taruser': taruser,
        'rtform': rtform,
        'pcount': function.get_privatemsg_count(request, request.user),
    })

    return render_to_response('home.html', varibles)

@login_required(login_url='/accounts/signin')
def rtweet(request, username, did):

    if request.method == 'POST':
        form = RTForm(request.POST)
        if form.is_valid():
            rtmessage = form.cleaned_data['rtmessage']
            orginmessage = get_object_or_404(Tweet, id=int(round(float(did))))
            t = Tweet.objects.create(message=rtmessage, user=request.user, orginmessage=orginmessage)
            messages.info(request, u'发送成功!')
            return HttpResponseRedirect(reverse('mblog_home'))
        else:
            raise Http404(u'表单验证失败!')
    else:
        raise Http404(u'发送失败!')




# 所有用户列表页

@login_required(login_url='/accounts/signin')
def userslist(request):

    users = User.objects.exclude(is_staff=True).exclude(
        username=request.user.username)

    paginator_info = paginatorer.paginator_parse(
        request, users, ITEMS_PRE_PAGE)

    varibles = RequestContext(request, {
        'page_title': 'userslist',
        'users': paginator_info['curremt_obj'],
        'paginator': paginator_info,
        'pcount': function.get_privatemsg_count(request, request.user),
    })
    return render_to_response('userslist.html', varibles)

@login_required(login_url='/accounts/signin')
def tweetdetail(request, username, did):

    if request.method == 'POST':
        form = ReplyForm(request.POST)
        if form.is_valid():
            subject = get_object_or_404(Tweet, id=int(did))
            replymessage = form.cleaned_data['replymessage']
            replyer = request.user
            r = Reply(subject=subject, replytweet=replymessage, replyer=replyer)
            r.save()
            messages.info(request, u'回复成功!')
            return HttpResponseRedirect(reverse('mblog_tweetdetail', args=[username, did]))
        else:
            raise Http404(u'表单验证失败!')
    else:
        form = ReplyForm()
        detailtweet = get_object_or_404(Tweet, id=int(did))
        replytweets = Reply.objects.filter(subject=detailtweet)
    varibles = RequestContext(request, {
        'page_title': 'tweetdetail',
        'form': form,
        'detailtweet': detailtweet,
        'replytweets': replytweets,
    })
    return render_to_response('tweetdetail.html', varibles)

@login_required(login_url='/accounts/signin')
def replytweet_del(request, username, subuser, did):

    replyer=get_object_or_404(User, username=subuser)
    reply = get_object_or_404(Reply, id=int(did))

    if username == request.user.username or reply.subject.user.username == subuser:
        reply.delete()
        messages.info(request, u'删除成功!')
        return HttpResponseRedirect(reverse('mblog_home'))
    else:
        raise Http404(u'非法操作!')

    return HttpResponse()

# 用户个人空间


@login_required(login_url='/accounts/signin')
def user_index(request, username):

    taruser = get_object_or_404(User, username=username)

    tweets = Tweet.objects.filter(user=taruser).order_by('-addtime')

    paginator_info = paginatorer.paginator_parse(
        request, tweets, ITEMS_PRE_PAGE)

    avatar_url = '/%savatar/150/%s' % (
        MEDIA_ROOT, taruser.profile.avatar)
    avatar_50_url = '/%savatar/50/%s' % (
        MEDIA_ROOT, taruser.profile.avatar)

    varibles = RequestContext(request, {
        'tweets': paginator_info['curremt_obj'],
        'avatar_url': avatar_url,
        'avatar_50_url': avatar_50_url,
        'paginator': paginator_info,
        'taruser': taruser,
        'pcount': function.get_privatemsg_count(request, request.user),
    })

    return render_to_response('user_index.html', varibles)


# 展示关注者
@login_required(login_url='/accounts/signin')
def followers(request, username):

    taruser = get_object_or_404(User, username=username)

    followerslist = [f.followers for f in taruser.follower_set.all()]

    paginator_info = paginatorer.paginator_parse(
        request, followerslist, ITEMS_PRE_PAGE)

    varibles = RequestContext(request, {
        'page_title': 'followerslist',
        'followerslist': paginator_info['curremt_obj'],
        'paginator': paginator_info,
        'taruser': taruser,
        'pcount': function.get_privatemsg_count(request, request.user),
    })
    return render_to_response('followers.html', varibles)

# 展示粉丝


@login_required(login_url='/accounts/signin')
def fans(request, username):

    taruser = get_object_or_404(User, username=username)
    fanslist = [f.fans for f in taruser.fan_set.all()]

    paginator_info = paginatorer.paginator_parse(
        request, fanslist, ITEMS_PRE_PAGE)

    varibles = RequestContext(request, {
        'page_title': 'fanslist',
        'fanslist': paginator_info['curremt_obj'],
        'paginator': paginator_info,
        'taruser': taruser,
        'pcount': function.get_privatemsg_count(request, request.user),
    })
    return render_to_response('fans.html', varibles)

# 添加关注


@login_required(login_url='/accounts/signin')
def follower_add(request, username, dfollower):
    try:
        f = Friendship(
            fans=request.user,
            followers=get_object_or_404(User, username=dfollower))
        f.save()
        messages.info(request, u'加关注成功!')
    except Exception as e:
        messages.info(request, u'已经关注了!')
    return HttpResponseRedirect(reverse('mblog_followers', args=[request.user]))


# 取消关注


@login_required(login_url='/accounts/signin')
def follower_del(request, username, dfollower):
    if username == request.user.username:
        f = get_object_or_404(Friendship,
                              fans=request.user,
                              followers=get_object_or_404(User, username=dfollower))
        f.delete()
        messages.info(request, u'取消关注成功!')
        return HttpResponseRedirect(reverse('mblog_followers', args=[request.user]))
    else:
        raise Http404(u'非法操作')
# 移出粉丝


@login_required(login_url='/accounts/signin')
def fan_del(request, username, dfan):
    if username == request.user.username:
        f = get_object_or_404(Friendship,
                              fans=get_object_or_404(User, username=dfan),
                              followers=request.user)
        f.delete()
        messages.info(request, u'移除粉丝成功!')
        return HttpResponseRedirect(reverse('mblog_fans', args=[request.user]))
    else:
        raise Http404(u'非法操作')

# 删除微博


@login_required(login_url='/accounts/signin')
def tweet_del(request, username, did):

    if username == request.user.username:
        t = get_object_or_404(Tweet, id=int(did))
        t.delete()
        messages.info(request, u'删除成功!')
        return HttpResponseRedirect(reverse('mblog_user_index', args=[request.user]))
    else:
        raise Http404(u'非法操作')


# 私信相关
def __privatemsg(request, username, privatemsglist, privatemsgin, template):

    if username == request.user.username:

        if privatemsgin == 'receiver':
            pms = PrivateMessage.objects.filter(receiver__in=list(privatemsglist)).filter(
                sender=request.user).order_by('-addtime')
        else:
            pms = PrivateMessage.objects.filter(sender__in=list(privatemsglist)).filter(
                receiver=request.user).order_by('-addtime')

        paginator_info = paginatorer.paginator_parse(
            request, pms, ITEMS_PRE_PAGE)

    else:
        raise Http404(u'非法操作')

    varibles = RequestContext(request, {
        'page_title': '私信列表',
        'pms': paginator_info['curremt_obj'],
        'paginator': paginator_info,
    })
    return render_to_response(template, varibles)


@login_required(login_url='/accounts/signin')
def receiverslist(request, username):

    senderslist = [pm.sender for pm in request.user.sender_set.all()]
    return __privatemsg(request, username, senderslist, 'sender', 'receiverslist.html')


@login_required(login_url='/accounts/signin')
def senderslist(request, username):
    receiverslist = [pm.receiver for pm in request.user.receiver_set.all()]
    return __privatemsg(request, username, receiverslist, 'receiver', 'senderslist.html')


@login_required(login_url='/accounts/signin')
def privatemsgdetail(request, username, did):

    pm = get_object_or_404(PrivateMessage, id=did)

    varibles = RequestContext(request, {
        'pm': pm,
        'pcount': function.get_privatemsg_count(request, request.user),
    })
    return render_to_response('privatemsgdetail.html', varibles)


@login_required(login_url='/accounts/signin')
def privatemsg_add(request, username, dreceiver):

    if request.method == 'POST':
        form = PrivateMessageForm(request.POST)
        if form.is_valid():

            sender = User.objects.get(username=username)
            receiver = User.objects.get(username=dreceiver)

            privatemsg = form.cleaned_data['privatemsg']

            pm = PrivateMessage.objects.create(
                sender=sender,
                receiver=receiver,
                privatemsg=privatemsg
            )
            pm.save()
            messages.info(request, u'发送成功!')
            return HttpResponseRedirect(reverse('mblog_senderslist', args=[request.user]))
    else:
        form = PrivateMessageForm()

    varibles = RequestContext(request, {
        'form': form,
        'receiver': dreceiver
    })
    return render_to_response('privatemsg_add.html', varibles)


@login_required(login_url='/accounts/signin')
def privatemsg_del(request, username, did):

    if username == request.user.username:
        pm = get_object_or_404(PrivateMessage, id=int(did))
        pm.delete()
        messages.info(request, u'删除成功!')
        return HttpResponseRedirect(reverse('mblog_receiverslist', args=[request.user]))
    else:
        raise Http404(u'非法操作')


def privatemsg_reader(request, username, did):

    if username == request.user.username:
        PrivateMessage.objects.filter(id=did).update(isreader='1')
        return HttpResponseRedirect(reverse('mblog_privatemsgdetail', args=[username, did]))
    else:
        raise Http404(u'非法操作')


# 收藏相关

def favoritelist(request, username):

    if username == request.user.username:
        favoritelist = request.user.favorite_set.all().order_by('-addtime')
    else:
        raise Http404(u'非法操作')
    varibles = RequestContext(request, {
        'page_title': u'收藏',
        'favoritelist': favoritelist,
        'pcount': function.get_privatemsg_count(request, request.user),
    })
    return render_to_response('favoritelist.html', varibles)




# def favorite_add(request, username, did):

#     if username == request.user.username:
#         taruser = get_object_or_404(User, username=username)
#         tartweet = get_object_or_404(Tweet, id=did)
#         f, created = Favorite.objects.get_or_create(favtweet=tartweet)

#         try:
#             f.favuser.get(username=username)
#             favorite_del(request, username, did)
#             return HttpResponseRedirect(reverse('mblog_home'))
#         except Exception, e:
#             f.favuser.add(taruser)
#             f.save()
#             messages.info(request, u'收藏成功!')
#             return HttpResponseRedirect(reverse('mblog_home'))
#     else:
#         raise Http404(u'非法操作')

def favorite_add(request, username, tid):

    if username == request.user.username:
        taruser = get_object_or_404(User, username=username)
        tartweet = get_object_or_404(Tweet, id=tid)
        f, created = Favorite.objects.get_or_create(favtweet=tartweet)
        f.favuser.add(taruser)
        f.save()
        messages.info(request, u'收藏成功!')
        return HttpResponseRedirect(reverse('mblog_home'))
    else:
        raise Http404(u'非法操作')

def favorite_del(request, username, fid):

    if username == request.user.username:
        taruser = get_object_or_404(User, username=username)
        try:
            f = Favorite.objects.get(id=fid)
            f.favuser.remove(taruser)
            messages.info(request, u'取消收藏!')
        except Exception, e:
            raise Http404(u'取消失败')
        return HttpResponseRedirect(reverse('mblog_home'))
    else:
        raise Http404(u'非法操作')


# 注册


def signup(request):

    if request.method == 'POST':
        form = RegistrationForm(request.POST)
        if form.is_valid():
            username = form.cleaned_data['username']
            password = form.cleaned_data['password']
            email = form.cleaned_data['email']

            user = User.objects.create_user(
                username=username,
                password=password,
                email=email
            )
            area = Area()
            area.save()
            p = Profile(
                user=user, area=Area.objects.get(id=1))
            p.save()
            userinfo = {
                'username': username,
                'password': password,
                'email': email,
            }

            mailer.send_regist_success_mail(userinfo)
            messages.info(request, u'注册成功！')
            return HttpResponseRedirect(reverse('mblog_signin'))

    else:
        if request.user.is_authenticated():
            return HttpResponseRedirect(reverse('mblog_home'))
        form = RegistrationForm()

    varibles = RequestContext(request, {
        'form': form
    })
    return render_to_response('accounts/signup.html', varibles)

# 登入


def signin(request):

    if request.method == 'POST':
        form = LoginForm(request.POST)
        if form.is_valid():
            username = form.cleaned_data['username']
            password = form.cleaned_data['password']
            user = authenticate(username=username, password=password)
            if user is not None:
                login(request, user)
                return HttpResponseRedirect('/')
            else:
                messages.info(request, u'用户名或密码错误！')
                return HttpResponseRedirect(reverse('mblog_signin'))
    else:
        if request.user.is_authenticated():
            return HttpResponseRedirect(reverse('mblog_home'))
        form = LoginForm()

    varibles = RequestContext(request, {
        'form': form,
    })
    return render_to_response('accounts/signin.html', varibles)

# 注销


@login_required(login_url='/accounts/signin')
def signout(request):
    logout(request)
    return HttpResponseRedirect(reverse('mblog_index'))

# 个人设置


@login_required(login_url='/accounts/signin')
def setting(request):

    if request.method == "POST":
        form = SettingForm(request.POST, request.FILES)
        if form.is_valid():
            # 头像修改
            if 'avatar' in request.FILES:
                avatar = request.FILES['avatar']

                state = uploader.upload_avatar(avatar)
                if state['success']:
                    print request.user.profile.id

                    Profile.objects.filter(user__id=request.user.id).update(
                        user=request.user,
                        avatar=state['message']
                    )

                    remessage = u'上传成功'
                    avatar_url = '/%s/avatar/150/%s' % (
                        MEDIA_ROOT, request.user.profile.avatar)
                else:
                    remessage = state['message']
                messages.info(request, remessage)
            else:
                try:
                    p = Profile.objects.get(user=request.user)
                    avatar_url = '/%savatar/150/%s' % (MEDIA_ROOT, p.avatar)
                    messages.info(request, u'头像保存成功')
                except Exception as e:
                    raise e
                if p.avatar is None:
                    messages.info(request, u'请选择上传的图片!')
                    return HttpResponseRedirect('.')
            # 用户名 个人主页 关于修改
            nickname = form.cleaned_data['nickname']
            homepage = form.cleaned_data['homepage']
            about = form.cleaned_data['about']

            Profile.objects.filter(user__id=request.user.id).update(
                user=request.user,
                nickname=nickname,
                homepage=homepage,
                about=about)

            # 密码修改
            password = form.cleaned_data['password']
            try:
                u = User.objects.get(username=request.user)
                u.set_password(password)
                u.save()
                messages.info(request, u'保存成功')
                return HttpResponseRedirect('.')
            except Exception as e:
                raise e

        else:
            messages.info(request, u'没有上传图片或者上传的图片不合法!')
            return HttpResponseRedirect('.')
    else:
        form = SettingForm()
        try:
            p = Profile.objects.get(user=request.user)
            if p.avatar == '':
                avatar_url = '/%savatar/default/default.png' % MEDIA_ROOT
            else:
                avatar_url = '/%savatar/150/%s' % (MEDIA_ROOT, p.avatar)
        except Exception as e:
            raise e

    varibles = RequestContext(request, {
        'page_title': u'个人设置',
        'form': form,
        'avatar_url': avatar_url,
        'pcount': function.get_privatemsg_count(request, request.user),
    })
    return render_to_response('settings.html', varibles)
